<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑用户' : '新增用户'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="15">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="formData.username"
              placeholder="请输入用户名"
              :disabled="isEdit"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="15">
          <el-form-item label="密码" prop="password">
            <el-input
                v-model="formData.password"
                type="password"
                :placeholder="isEdit ? '不修改请留空' : '请输入密码'"
                show-password
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="15">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="15">
          <el-form-item label="手机号" prop="phone">
            <el-input
                v-model="formData.phone"
                placeholder="请输入手机号"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="账户类型" prop="accountType">
            <el-select
              v-model="formData.accountType"
              placeholder="请选择账户类型"
              style="width: 100%"
            >
              <el-option 
                v-for="(text, value) in ACCOUNT_TYPE_TEXT" 
                :key="value"
                :label="text" 
                :value="Number(value)" 
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="状态" prop="status">
            <el-select
                v-model="formData.status"
                placeholder="请选择状态"
                style="width: 100%"
            >
              <el-option
                  v-for="(text, value) in USER_STATUS_TEXT"
                  :key="value"
                  :label="text"
                  :value="Number(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          {{ loading ? '保存中...' : '确定' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '../api/user'
import { ACCOUNT_TYPE_TEXT, USER_STATUS_TEXT } from '../utils/constants'
import { validateUsername, validatePassword, validateEmail, validatePhone } from '../utils/validate'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  email: '',
  phone: '',
  accountType: 2,
  status: 1
})

// 表单验证规则
const formRules = {
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword(props.isEdit), trigger: 'blur' }],
  email: [{ validator: validateEmail, trigger: 'blur' }],
  phone: [{ validator: validatePhone, trigger: 'blur' }],
  accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 监听visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    resetForm()
    if (props.isEdit && props.userData) {
      Object.assign(formData, {
        ...props.userData,
        password: '' // 编辑时密码置空
      })
    }
  }
})

// 监听dialogVisible变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    username: '',
    password: '',
    email: '',
    phone: '',
    accountType: 2,
    status: 1
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const submitData = { ...formData }
    
    // 如果是编辑且密码为空，则不传递密码字段
    if (props.isEdit && !submitData.password) {
      delete submitData.password
    }
    
    if (props.isEdit) {
      await userApi.updateUser(props.userData.id, submitData)
      ElMessage.success('更新用户成功')
    } else {
      await userApi.createUser(submitData)
      ElMessage.success('创建用户成功')
    }
    
    emit('success')
    handleClose()
    
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error(error.message || '保存用户失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
